package com.ms.service.impl;

import com.ms.mapper.AdminLeaveMapper;
import com.ms.mapper.ApprovalRecordMapper;
import com.ms.pojo.Approval_record;
import com.ms.pojo.Leave_apply;
import com.ms.service.AdminLeaveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class AdminLeaveServiceImpl implements AdminLeaveService {

    @Autowired
    private AdminLeaveMapper adminLeaveMapper;
    @Autowired
    private ApprovalRecordMapper approvalRecordMapper;
    /**
     * 获取所有未审批的请假记录
     * @return 请假记录列表
     */
    @Override
    public List<Leave_apply> list() {
        List<Leave_apply> list = adminLeaveMapper.list();
        return list;
    }

    /**
     * 根据ID获取请假详情
     * @param id 请假ID
     * @return 请假详情
     */
    @Override
    public Leave_apply getById(Integer id) {
       Leave_apply  leave = adminLeaveMapper.getById(id);
       return leave;
    }

    /**
     * 事务管理：确保请假状态更新和审批记录保存同时成功/失败
     */
    @Transactional
    @Override
    public boolean updateStatus(Integer id, Integer status, Integer approverId, String approvalOpinion) {

        // 参数校验
        if (id == null || status == null || approverId == null) {
            return false;
        }

        // 1. 更新请假申请状态
        int updateResult = adminLeaveMapper.updateStatus(id, status);
        if (updateResult <= 0) {
            return false; // 如果没有影响任何行，则更新失败
        }

        // 2. 保存审批记录
        Approval_record record = new Approval_record();
        record.setApplyType(1); // 申请类型：请假
        record.setApplyId(id); // 关联的请假记录ID
        record.setApproverId(approverId); // 审批人ID
        record.setApprovalResult(status); // 审批结果（与请假状态一致）
        record.setApprovalOpinion(approvalOpinion); // 审批意见
        record.setApprovalTime(new Date()); // 添加审批时间

        int insertCount = approvalRecordMapper.insert(record);
        return insertCount > 0;
    }
}
